import { defineComponent, ref, computed } from 'vue'
import { usePrefix, useChildren } from '../hooks'
import { IconWidget } from '../widgets'
import cls from 'classnames'

export const PANEL_KEY = Symbol('PANEL_KEY')

export const CompositePanel = defineComponent({
  setup(_, { slots }) {
    const prefix = usePrefix('composite-panel')
    const { linkChildren, children } = useChildren(PANEL_KEY)

    const defaultActiveKey = ref(0)

    const activeKey = computed(() => defaultActiveKey.value)

    const setDefaultActiveKey = (value: number) => {
      if (defaultActiveKey.value === value) return
      defaultActiveKey.value = value
    }

    linkChildren({ activeKey, setDefaultActiveKey })

    const takeTab = (item: any) => {
      if (item.href) {
        return <a href={item.href}>{item.icon}</a>
      }
      return <IconWidget infer={item.icon} size={22}></IconWidget>
    }

    const handleTabClick = (index: number) => {
      setDefaultActiveKey(index)
    }

    const renderPanelIcon = () => {
      return children.map((item: any, index: number) => {
        const shape = item.shape ?? 'tab'
        const Comp = shape === 'link' ? 'a' : 'div'

        return (
          <Comp
            class={cls(prefix + '-tabs-pane', {
              active: activeKey.value === index,
            })}
            key={index}
            href={item.href}
            onClick={() => handleTabClick(index)}
          >
            {takeTab(item)}
          </Comp>
        )
      })
    }

    return () => (
      <div class={cls(prefix)}>
        <div class={prefix + '-tabs'}>{renderPanelIcon()}</div>
        {slots.default?.()}
      </div>
    )
  },
})
